package com.fa.ojcodesandbox.docker;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.Image;
import com.github.dockerjava.api.model.PullResponseItem;
import com.github.dockerjava.core.DockerClientBuilder;

import java.util.List;

/**
 * ClassName: DockerDemo
 * Package: com.fa.ojcodesandbox.docker
 * Description:
 *
 * @Author:
 * @Create: 2024/5/1 - 10:14
 * @Version: v1.0
 */
public class DockerDemo {
    public static void main(String[] args) throws InterruptedException {
        // 获取默认的 Docker Client
        DockerClient dockerClient = DockerClientBuilder.getInstance().build();
//        PingCmd pingCmd = dockerClient.pingCmd();
//        pingCmd.exec();

        // 拉取镜像     这里需要指定下载镜像的版本，否则会下载所有版本
        String image = "nginx:latest";
        /*PullImageCmd pullImageCmd = dockerClient.pullImageCmd(image);
        PullImageResultCallback pullImageResultCallback = new PullImageResultCallback() {
            @Override
            public void onNext(PullResponseItem item) {
                System.out.println("下载镜像：" + item.getStatus());
                super.onNext(item);
            }
        };
        pullImageCmd.exec(pullImageResultCallback)
                .awaitCompletion();
        System.out.println("下载完成");*/

        //查看镜像
        ListImagesCmd listImagesCmd = dockerClient.listImagesCmd();
        List<Image> imageList = listImagesCmd.withShowAll(true).exec();
        System.out.println("imageList = " + imageList);
        for (Image img: imageList) {
            System.out.println("img = " + img);
        }

        // 创建容器
        /*CreateContainerCmd containerCmd = dockerClient.createContainerCmd(image);
        CreateContainerResponse createContainerResponse = containerCmd.withCmd("echo", "Hello Docker")
                .exec();
        System.out.println(createContainerResponse);*/

        // 查看容器状态
        /*ListContainersCmd listContainersCmd = dockerClient.listContainersCmd();
        List<Container> containerList = listContainersCmd.withShowAll(true).exec();
        for (Container container:
             containerList) {
            System.out.println("container=" + container);
        }

        // 启动容器
        StartContainerCmd startContainerCmd = dockerClient.startContainerCmd(containerList.get(0).getId());
        startContainerCmd.exec();*/
    }
}
